package com.hq.play.util;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hq.play.base.data.PageData;
import com.hq.play.base.data.Result;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;

/**
 * 联网服务用于获取网络数据
 */
public class HttpSevvice implements IhttpService {
    private OkHttpClient client;
    private Retrofit retrofit;
    private ListeningExecutorService pool;

    public HttpSevvice(ListeningExecutorService pool) {
        this.pool = pool;
        this.init();
    }

    /**
     * 服务初始化
     */
    private void init() {
        // 创建Dispatcher实例
        Dispatcher dispatcher = new Dispatcher();
        // 设置最大并发请求数
        dispatcher.setMaxRequests(64);
        // 设置每个主机的最大并发请求数
        dispatcher.setMaxRequestsPerHost(64);
        // 创建连接池实例
        ConnectionPool pool = new ConnectionPool(20, 5L, TimeUnit.MINUTES);
        // 创建连接池实例
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectionPool(pool);
        builder.dispatcher(dispatcher);
        builder.connectTimeout(30L, TimeUnit.SECONDS);
        builder.readTimeout(30L, TimeUnit.SECONDS);
        builder.writeTimeout(30L, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        this.client = builder.build();

    }

    private void RetrofitClient(String host) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Result.class, new Result())
                .create();

        this.retrofit = new Retrofit.Builder()
                .baseUrl(host)
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(this.client)
                .build();

    }

    /**
     * 创建 联网 api 实力
     *
     * @param cls  api 实力
     * @param host 主机 ip
     * @param <T>  api 实力
     * @return api 实力
     */
    public final <T> T createApi(Class<T> cls, String host) {
        if (host == null || host.equals("")) {
            return this.retrofit.create(cls);
        }
        RetrofitClient(host);
        return this.retrofit.create(cls);
    }


    /**
     * @param pageNum  当前页码
     * @param pageSize 每页显示条数
     * @return
     */
    @Override
    public ListenableFuture<PageData> ResultPagVideo(int pageNum, int pageSize) {
     //   Log.d("HttpSevvice", "页面 : " + pageNum);
        try {
            ListenableFuture<PageData> lf = this.pool.submit(new Callable<PageData>() {
                @Override
                public PageData call() throws Exception {
                    String host = "http://192.168.1.254:81/";
                    Api api = createApi(Api.class, host);
                    Result r = api.pagVideo(pageNum, pageSize).execute().body();
                    if (r != null && r.getCode() == 200) {
                        PageData pd = r.getData();
                        if (pd != null) {
                            pd.setPageNum(pageNum);
                            return pd;
                        }

                    }
                    return null;
                }
            });


            return lf;
        } catch (Exception e) {

        }
        return null;
    }

    private interface Api {
        /**
         * * 分页关联查询所有视频信息
         * * 分组类型 分组位置 视频标题 视频简介 视频封面 视频地址 视频时长
         * * 排序根据视频更新时间升序
         * * @param pageNum  当前页码
         * * @param pageSize 每页显示条数
         */
        @GET("videoMessage/index&pageNum={pageNum}&&pageSize{pageSize}")
        Call<Result> pagVideo(@Path("pageNum") int pageNum, @Path("pageSize") int pageSize);
    }
}
